package edu.pitt.dbmi.odie.gapp.gwt.server.util.gdata;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class ODIE_DocumentEntitySAXParser extends DefaultHandler {
	
	private XMLReader parser;         // Reuse the parser across multiple calls
	private StringBuffer accumulator; // Accumulate text
	private ODIE_GDataDocument odieGDataDocument;
	
	public static ODIE_DocumentEntitySAXParser singleton = null ;
	
	public static ODIE_DocumentEntitySAXParser getInstance() {
		if ( singleton == null) {
			 singleton = new ODIE_DocumentEntitySAXParser()  ;
		}
		return  singleton ;
	}
	
	public ODIE_DocumentEntitySAXParser() {
		try {
			this.parser = new SAXParser();
			parser.setFeature("http://xml.org/sax/features/validation",
					false);
			parser.setContentHandler(this);
			parser.setErrorHandler(this);
		} catch (SAXNotRecognizedException e) {
			e.printStackTrace();
		} catch (SAXNotSupportedException e) {
			e.printStackTrace();
		}
	}
	
	public void parseDocument(String documentEntryXml) {
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(documentEntryXml.getBytes()) ;
			InputSource input = new InputSource(bis);
			input.setEncoding("ISO-8859-1");
			parser.parse(input) ;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}
	
	public void startDocument() {
		odieGDataDocument = new ODIE_GDataDocument() ;
		accumulator = new StringBuffer();
	}

	public void characters(char[] buffer, int start, int length) {
		accumulator.append(buffer, start, length);
	}

	public void startElement(String namespaceURL, String localName,
			String qname, Attributes attributes) {
			accumulator.setLength(0);
	}

	public void endElement(String namespaceURL, String localName, String qname) {
		try {
			String accumulatorValue = accumulator.toString().trim();
			if (qname.equals("gd:resourceId")) {
				this.odieGDataDocument.setRawId(accumulatorValue) ;
			} 
			if (qname.equals("atom:id")) {
				this.odieGDataDocument.setAtomId(accumulatorValue) ;
			}
			if (qname.equals("atom:title")) {
				this.odieGDataDocument.setTitle(accumulatorValue) ;
			}
			
		} catch (Exception x) {
			x.printStackTrace();
		}
	}
	

	public ODIE_GDataDocument getOdieGDataDocument() {
		return odieGDataDocument;
	}

	public void setOdieGDataDocument(ODIE_GDataDocument odieGDataDocument) {
		this.odieGDataDocument = odieGDataDocument;
	}
}
